package lei.m_线程池_事物;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 高性能版本：结合无锁和有锁操作的优化示例
 */
public class HighPerformanceThreadPoolExampleV3 {

    // 高性能线程池配置
    private static final int THREAD_COUNT = Math.min(Runtime.getRuntime().availableProcessors() * 2, 8);
    private static final ExecutorService executor = Executors.newFixedThreadPool(THREAD_COUNT);

    // 无锁银行账户实现
    static class LockFreeBankAccount {
        private final String accountId;
        private final AtomicLong balance; // 使用原子类避免锁

        public LockFreeBankAccount(String accountId, long initialBalance) {
            this.accountId = accountId;
            this.balance = new AtomicLong(initialBalance);
        }

        // 无锁转账操作
        public boolean transferTo(LockFreeBankAccount toAccount, long amount) {
            long currentBalance = balance.get();

            // 检查余额
            if (currentBalance < amount) {
                return false;
            }

            // 使用CAS操作进行转账
            if (balance.compareAndSet(currentBalance, currentBalance - amount)) {
                // 转出成功，增加对方账户余额
                toAccount.balance.addAndGet(amount);
                return true;
            }

            return false; // 转出失败
        }

        public long getBalance() {
            return balance.get();
        }

        public String getAccountId() {
            return accountId;
        }
    }

    // 共享账户
    private static final LockFreeBankAccount accountA = new LockFreeBankAccount("ACCOUNT_A", 100000L);
    private static final LockFreeBankAccount accountB = new LockFreeBankAccount("ACCOUNT_B", 100000L);
    private static final LockFreeBankAccount accountC = new LockFreeBankAccount("ACCOUNT_C", 100000L);

    public static void main(String[] args) {
        System.out.println("=== 高性能无锁转账示例 ===");
        System.out.println("初始余额: A=" + accountA.getBalance() +
                ", B=" + accountB.getBalance() +
                ", C=" + accountC.getBalance());

        long startTime = System.currentTimeMillis();

        // 提交大量并发任务
        CountDownLatch latch = new CountDownLatch(20);

        for (int i = 0; i < 20; i++) {
            final int taskId = i;
            executor.submit(() -> {
                try {
                    performHighPerformanceTransfer(taskId);
                } finally {
                    latch.countDown();
                }
            });
        }

        // 等待所有任务完成
        try {
            latch.await(5, TimeUnit.SECONDS); // 设置超时时间
        } catch (InterruptedException e) {
            System.err.println("等待任务完成时被中断");
            Thread.currentThread().interrupt();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("=== 最终余额 ===");
        System.out.println("账户A余额: " + accountA.getBalance());
        System.out.println("账户B余额: " + accountB.getBalance());
        System.out.println("账户C余额: " + accountC.getBalance());
        System.out.println("总余额: " + (accountA.getBalance() + accountB.getBalance() + accountC.getBalance()));
        System.out.println("总执行时间: " + (endTime - startTime) + " ms");

        executor.shutdown();
    }

    private static void performHighPerformanceTransfer(int taskId) {
        boolean success = false;

        switch (taskId % 3) {
            case 0:
                success = accountA.transferTo(accountB, 50L);
                break;
            case 1:
                success = accountB.transferTo(accountC, 30L);
                break;
            case 2:
                success = accountC.transferTo(accountA, 20L);
                break;
        }

        if (success) {
            System.out.println("任务 " + taskId + " 转账成功，线程: " + Thread.currentThread().getName());
        }
    }
}
